# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
*
*
*
"""     
import sys #system calls
import re # re.search
import datetime 
import csv #save report
import os
import string

class formatdate:
    def fda(self, date, hours):
        year, month, day = date
        hour, minute, second = hours
        try:
            if datetime.datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute), second=int(second)):
                date = datetime.datetime(year=int(year), month=int(month), day=int(day), hour=int(hour), minute=int(minute), second=int(second))
                format = str(date) + "Z"
                format = format.replace(" ", "T")
                return format
        except:
            pass

    def checkdataformat(self, d):
        t = formatdate()
        format = str(t.timeconvert(float(d))) + "Z"
        format = format.replace(" ", "T")
        return format
    
    def timeconvert(self, longdata):
        converted = datetime.datetime.fromtimestamp(longdata).strftime('%Y-%m-%d %H:%M:%S')
        return converted



class mapImpact(str):
    def mapImpactValue(self):
        impactOut = {"A":"1","B":"2","C":"3","D":"4", "E":"5", "":""}
        return impactOut.pop(self)

def openLog(logfile):
    """
    Function openLog(logfile)
    Receive argument log file ant try to open in read mode
    Exception if could not open the file
    """
    try:
        log=open(logfile, 'rb')
        return log
    except Exception, e:
        print "[-] " + str(e)
        sys.exit()

def readLog(filename,log):
    """
    Function readLog(log)
    """
    reader = csv.reader(log, dialect='excel')
    composenewfilename = os.path.splitext(filename)[0] + "_translated.csv"
    outfile = csv.writer(open(composenewfilename,'w'), dialect='excel')
    for line in reader:
        if re.search("ID", str(line)):
            outfile.writerow(("Case ID","Commencement Date","Termination Date","Impact","Case Name","Case Information","User Identifier"))
        else:
            try:
                caseid, cdate, tdate, impact, cname, iuser, identifier = line
            except Exception, e:
                print "[-] " + str(e)
            if not caseid=="":
                cd = formatdate()
                if cdate.isdigit():
                    cdate = cd.checkdataformat(cdate)
                elif not cdate == "":
                    try:
                        cdate = cdate.split(" ")
                        chour = cdate[1].split(":")
                        cdate = cdate[0].split("/")
                        cdate.reverse()
                        cdate = cd.fda(cdate, chour)
                    except Exception, e:
                        print "[-] " + str(e)
                    if cdate == None:
                        continue
                elif cdate == "":
                    cdate = ""
                ###############################
                td = formatdate()
                if tdate.isdigit():
                    tdate = td.checkdataformat(tdate)
                elif not tdate == "":
                    try:
                        tdate = tdate.split(" ")
                        thour = tdate[1].split(":")
                        tdate = tdate[0].split("/")
                        tdate.reverse()
                        tdate = td.fda(tdate, thour)
                    except Exception, e:
                        print "[-] " + str(e)
                    if tdate == None:
                        continue
                elif tdate == "":
                    tdate = ""
                ###############################
                #Check Impact Table atributions
                impact = mapImpact(impact)
                if impact.mapImpactValue() == None:
                    continue
                ###############################
                if identifier == "":
                    continue
                ###############################
                x = caseid , cdate , tdate , str(impact.mapImpactValue()) , str(cname.upper()) , str(iuser.upper()) , str(identifier.upper())
                outfile.writerow(x)
    #######################
   
def main():
    """
    main funtion
    first openLog file function and readLog function
    arguments obtained with optparse
    """
    if (len(sys.argv) < 2):
        print "\nUsage: scrypt.py <csv file> \n"
        sys.exit()
    else:
        cfile = sys.argv[1]
        savelog=openLog(cfile)
        try:
            readLog(cfile,savelog)
            print "Done!" 
        except Exception, e:
            print "[-] " + str(e)
 
if __name__ == '__main__':
    main()
